package com.mengdee.manage.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mengdee.manage.validator.UserDetail;
import com.mengdee.manage.validator.UserEntity;
import com.mengdee.manage.validator.UserModel;

@Controller
@RequestMapping("/Valid")
public class ValidController extends BaseController {
	
	// http://localhost:8081/platform-springmvc-webapp/Valid/test?age=18&nickname=mengdee&id=1&email=123@qq.com&password=root123&username=123&phone=18321758957
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public @ResponseBody Object validation(HttpServletRequest request, @Valid UserModel user, BindingResult bindingResult){
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			
			return super.ResponseJsonError(fieldError);
		}
		
		return "ok";
	}
	
	// 一个方法同时校验多个对象需要绑定多个结果BindingResult，出现一个@Valid就对应后面声明的一个BindingResult
	@RequestMapping(value = "/test2", method = RequestMethod.GET)
	public @ResponseBody Object validationMore(HttpServletRequest request, 
			@Valid UserModel user, BindingResult bindingResult,
			@Valid UserDetail userDetail, BindingResult bindingResult2){
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			
			return super.ResponseJsonError(fieldError);
		}
		
		if (bindingResult2.hasErrors()) {
			FieldError fieldError = bindingResult2.getFieldError();
			
			return super.ResponseJsonError(fieldError);
		}
		
		return "ok";
	}
	
//	http://localhost:8081/platform-springmvc-webapp/Valid/test3?address=123&company=456&phone=123
	@RequestMapping(value = "/test3", method = RequestMethod.GET)
	public @ResponseBody Object validationCustomAnnotation(HttpServletRequest request, 
			@Valid UserDetail userDetail, BindingResult bindingResult){
		if (bindingResult.hasErrors()) {
			FieldError fieldError = bindingResult.getFieldError();
			
			return super.ResponseJsonError(fieldError);
		}
		
		return "ok";
	}
	
}
